import React, { useState, useEffect } from 'react';

import { renderToString } from 'react-dom/server';
import { Space, Select, message, Button, Card } from 'antd';
import { manage, getSimpleSuggest } from '@/pages/scale/service/compose';
import ScaleSuggestList from '@/pages/scale/components/ScaleSuggestList';

import { formatDateFromTime } from '@/utils/format';
import copy from 'copy-to-clipboard';

const { htmlToText } = require('html-to-text');

const { Option } = Select;

/**
 * 訓練建議
 */
function ScaleTrainingSuggest({ user = {} }) {
  const [records, setRecords] = useState({ content: [] });
  const [suggests, setSuggests] = useState();
  const [checkSuggests, setCheckSuggests] = useState([]);

  /**
   * 帶出有目標的報告
   */
  const querySimpleSuggest = async (id) => {
    setSuggests(await getSimpleSuggest({ id }));
  };

  const queryRecords = async (number) => {
    setRecords(await manage({ values: { userNumber: number, suggest: true } }));
  };

  const copyToText = () => {
    const html = renderToString(<ScaleSuggestList items={suggests} value={checkSuggests} />);

    const text = htmlToText(html, {
      wordwrap: 130,
    });

    copy(text);
    message.success('复制成功');
  };

  useEffect(() => {
    if (user.visitingCodeV) {
      queryRecords(user.visitingCodeV);
    }
    return () => {};
  }, [user.visitingCodeV]);

  return (
    <Space direction="vertical">
      {records.content.length > 0 && (
        <Card
          bordered={false}
          style={{ width: '100%' }}
          title={
            <Select
              placeholder="请选择报告"
              style={{ width: '350px' }}
              onChange={(value) => {
                querySimpleSuggest(value);
              }}
            >
              {records.content.map(({ id, scaleName, reportDate }) => (
                <Option key={id} value={id}>
                  {scaleName} {formatDateFromTime(reportDate)}
                </Option>
              ))}
            </Select>
          }
          extra={
            suggests && (
              <Button type="primary" onClick={copyToText}>
                复制
              </Button>
            )
          }
        >
          {suggests && (
            <ScaleSuggestList
              items={suggests}
              value={checkSuggests}
              onChange={(checks) => {
                setCheckSuggests(checks);
              }}
            />
          )}
        </Card>
      )}
    </Space>
  );
}

export default ScaleTrainingSuggest;
